<?php
if(!isset($valid_controller)||$valid_controller===false)
{
  return;
}
//include_once $_SERVER['DOCUMENT_ROOT']."/math-videos/configure.inc.php";
//check if you have curl loaded
//echo $_REQUEST['json'];
//assign all valable  null value;
$title ='';
$abstract ='';
$lectureDate ='';
$duration ='';
$type ='';
$remoteURL= '';
$location= '';
$eventTitle= '';
$mscNumbers= '';
$keywords= '';
$familyName= '';
$givenName= '';
$middleName= '';
$suffix= ''; 
$altName= ''; 
$title= ''; 
$department= ''; 
$company= ''; 
$timecode= ''; 
$timecode_type= ''; 
$data= ''; 

$rating='';
$views='';
$thumbnail ='';
$timecode_sha1='';
$asset_title ='';
$data_string = json_decode($_REQUEST['json'],true); 
//$asset_array= array();
//$presenter_array = array();
//$timecode_array = array();
//foreach ($decoded as $item) {
//   $b_pag_bo_id[] = $item['b_pag_bo_id'];
 //  $b_pag_user_id[] = $item['b_pag_user_id'];
//}
foreach($data_string as $key=>$value)
{
	if($key=='presenters')
	{
		if(is_array($value))
		{ 
			unset($presenters_array);
			if(isset($value[0]))
			{
				
				for($i=0;$i<count($value);$i++)
				{
					foreach($value as $key1=>$value1)
					{
						 $$key1 = trim($value1);
					//	 echo "$key1 = $value1<br>";
						 $presenters_array[$i][$key1]=$value1;
					}
				}
			}
			else
			{
				 foreach($value as $key1=>$value1)
					{
						 $$key1 = trim($value1);
					//	 echo "$key1 = $value1<br>";
						 $presenters_array[0][$key1]=$value1;
					}
			}
		}
	}	
	elseif($key=='timecode')
	{
		if(is_array($value))
		{ 
		  unset($timecode_array);
			if(isset($value[0]))
			{
				for($i=0;$i<count($value);$i++)
				{
					foreach($value[$i] as $key2=>$value2)
					{
						 $$key2 = trim($value2);
					//	 echo "$key2 = $value2<br>";
						 $timecode_array[$i][$key2]=$value2;
					}					
				}
			}
			else
			{
				 foreach($value as $key2=>$value2)
					{
						 $$key2 = trim($value2);
					//	 echo "$key2 = $value2<br>";
						 $timecode_array[0][$key2]=$value2;
					}	
			}
		}
	}
	elseif($key=='keywords')
	{
		if(is_array($value))
		{ 
		  unset($keyword_array);
			 sort($value);
			for($t=0;$t<count($value); $t++)
			{
				$keyword_array[]=$value[$t];
			}
		}
	}
	elseif($key=='mscNumbers')
	{
		if(is_array($value))
		{ 
		  unset($msc_array);
		  sort($value);
			for($t=0;$t<count($value); $t++)
			{
				$msc_array[]=$value[$t];
			}
		}
	}
	elseif($key=='thumbnail')
	{
		if(is_array($value))
		{ 
		  unset($thumbnail_array);
		  foreach($value as $key2=>$value2)
			{
				$$key2 = trim($value2);
				//$thumbnail_array[$key2]=$value2;
				//	$thumbnail_array[$key2]= unserialize(gzuncompress(stripslashes(base64_decode(strtr($value2, '-_,', '+/=')))));
				if($key2 == 'image')
				{
					//$thumbnail_array[$key2]=urldecode($value2);
					//$thumbnail_array[$key2]=$value2;
					$thumbnail_array[$key2]= unserialize(gzuncompress(stripslashes(base64_decode(strtr($value2, '-_,', '+/=')))));
				}
				else
				{
					$thumbnail_array[$key2]=$value2;
				}
			}	
		}
	}
	else
	{
		$$key = trim($value);
	// echo "$key = $value<br>";
		if($key=='title')
		{
			$asset_title = $title;
		}
	}
unset( $key, $value );

} 

//authertication user
$sqltext="select id as user_id, institute_id from users  WHERE username=? and password=?";
$params = array();

array_push($params,sql_escape($username));
array_push($params,sql_escape($password));
$result = db_select_query($conn2,$sqltext,$params);
$user_id='';
$institute_id='';
while($row = db_fetch_array($result))
{
	$user_id = $row['user_id'];
	$institute_id = $row['institute_id'];
}
if($user_id =='')
{
	//echo "HTTP/1.1 401 <br />";
//	echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
//	echo "Location: https://api.mathinstitutes.org/metadata/v1/asset/2341<br />";
	//echo "{\"error\": \"Authorization Required\"}";
	//header('WWW-Authenticate: Basic Realm="Login please"');
  header('HTTP/1.0 401 Unauthorized');
	echo "{\"error\": \"Authorization Required\"}";
	//print_r(get_headers('http://www.mathinstitutes.org/math-videos/api/?mode=insert',1) );
    exit;
}
else
{
	/*aeeset:
	title, abstract, lectureDate, duration, type, remoteURL, location, eventTitle,
mscNumbers, keywords, presenters 
Presenters:
familyName, givenName, middleName, suffix, altName, title, department, company
Timecode:
timecode, type, data*/
  
	//check required fields
	
	//“error”: “missing required field - title”//
	$error_message ='';
	if(!isset($asset_title) ||  $asset_title=='')
	{
		$error_message .= "{\"error\": \"missing required field - title\"}";
	}
	if(!isset($lectureDate) ||  $lectureDate=='')
	{
	 $error_message .= "{\"error\": \"missing required field - lectureDate\"}";
	}
	if(!isset($remoteURL) ||  $remoteURL=='')
	{
	 $error_message .= "{\"error\": \"missing required field - remoteURL\"}";
	}
	if(!isset($location)||  $location=='' )
	{
	 $error_message .= "{\"error\": \"missing required field - location\"}";
	}
	if(!isset($presenters_array))
	{
	 $error_message .= "{\"error\": \"missing required field - presenter\"}";
	}
	if($error_message  =='')
	{
		//build checksum
		$presenter_checksum='';
		if(isset($presenters_array))
		{
			unset($presenters_list);
			for($i=0;$i<count($presenters_array); $i++)
			{
				foreach($presenters_array[$i] as $key=>$value)
				{
					 $$key = trim($value);
				}				
				$presenters_list[] = $familyName.$givenName.$middleName.$suffix.$altName.$title.$department.$company;		
			}
			if(isset($presenters_list) )
			{
				sort($presenters_list);
				for($i=0;$i<count($presenters_list); $i++)
				{
					$presenter_checksum .= $presenters_list[$i];
				}
			}
		}
		$timecode_checksum='';
		if(isset($timecode_array))
		{
			unset($timecode_list);
			for($i=0;$i<count($timecode_array); $i++)
			{
				foreach($timecode_array[$i] as $key=>$value)
				{
					 $$key = trim($value);
				}				
				$timecode_list[] = $timecode.$timecode_type.$data;		
			}
			if(isset($timecode_list) )
			{
				sort($timecode_list);
				for($i=0;$i<count($timecode_list); $i++)
				{
					$timecode_checksum .= $timecode_list[$i];
				}
			}
			$timecode_sha1 = sha1($timecode_checksum);
		}
		//sort keywords, mscNumber
		$msc_list ='';
		if(isset($msc_array))
		{
			for($i=0;$i<count($msc_array); $i++)
			{
				$msc_list .= $msc_array[$i];
			}
			
		}
		$keywords_list ='';
		if(isset($keyword_array))
		{
			for($i=0;$i<count($keyword_array); $i++)
			{
				$keywords_list .= $keyword_array[$i];
			}
			
		}
		
		$asset_string =$asset_title.$abstract.$lectureDate.$duration.$type.$remoteURL.$location.$eventTitle.$msc_list.$keywords_list.$presenter_checksum;
		//echo date("Y-m-d H:i:s",$lectureDate);
		//echo $asset_string."<br>";
		//exit();
		$asset_sha1 = sha1($asset_string);
		$statistics_sha1 ='';
		if($rating!='' || $views!='')
		{
			$statistics_sha1 = sha1($rating.$views);
		}
		$thumbnail_sha1 ='';
		if(isset($thumbnail_array) && $thumbnail_array !='' )
		{			
			$thumbnail_sha1 = sha1($thumbnail_array['image'].$thumbnail_array['type']);
		}
		//check if this asset is already added according the asset_sha1
		$sqltext = "SELECT id as check_id FROM asset WHERE assetSHA1=? ";
		$params = array();
		array_push($params,sql_escape($asset_sha1));
    $result = db_select_query($conn,$sqltext,$params);
		$check_num=0;
		while($row = db_fetch_object($result))
		{
			$check_num++;
		}
		if($check_num==0)
		{
			//insert to asset table 
	
			$sqltext="INSERT INTO asset(title, abstract, lecture_date, duration, asset_type, abstract_url, remote_url, location, event_title, created_datetime, created_by, last_modified_datetime, last_modified_by, rating, views, institute_id, assetSHA1, timecodeSHA1,statisticsSHA1, thumbnailSHA1,thumbnail_type) values( ?, ?, ?, ?, ? ,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			$params = array();
			array_push($params,sql_escape($asset_title));
			array_push($params,sql_escape($abstract));
			//array_push($params,date("Y-m-d",strtotime($lectureDate)));
			array_push($params,date("Y-m-d H:i:s",$lectureDate));
			if($duration =='')
			{
				 array_push($params,sql_escape(0));
			}
			else
			{
				 array_push($params,sql_escape($duration));
			}
			
			array_push($params,sql_escape($asset_type));
			array_push($params,sql_escape($abstract_url));
			array_push($params,sql_escape($remoteURL));
			array_push($params,sql_escape($location));
			array_push($params,sql_escape($eventTitle));
			array_push($params,date("Y-m-d H:i:s"));
			array_push($params,sql_escape($user_id));
			array_push($params,date("Y-m-d H:i:s"));// insert record, modified_date_time = created_date_time
			array_push($params,sql_escape($user_id));
			if($rating =='')
			{
				 array_push($params,sql_escape(0));
			}
			else
			{
				 array_push($params,sql_escape($rating));
			}
			
			if($views =='')
			{
				 array_push($params,sql_escape(0));
			}
			else
			{
				 array_push($params,sql_escape($views));
			}
			
			array_push($params,sql_escape($institute_id));
			array_push($params,sql_escape($asset_sha1));
			array_push($params,sql_escape($timecode_sha1));
			array_push($params,sql_escape($statistics_sha1));
			array_push($params,sql_escape($thumbnail_sha1));
			if(isset($thumbnail_array) && $thumbnail_array !='' )
			{			
				//$image_name =$id."_thumb".$thumbnail_array['type'];
			//	array_push($params,sql_escape($image_name ));
				array_push($params,sql_escape($thumbnail_array['type']));
			}
			else
			{
			//	array_push($params,'');
				array_push($params,'');
			}
			//print($sqltext);
		//	print_r($params);
			
			db_change_query($conn,$sqltext,$params);
			$sqltext = "SELECT id FROM asset ORDER BY id DESC LIMIT 1";
			$params = array();
			$result = db_select_query($conn,$sqltext,$params);
			while($row = db_fetch_object($result))
			{
				foreach ($row as $key => $value) 
				{
					$value = trim($value);
					$$key= $value;
				}
			}
		 // thumbnail
			if(isset($thumbnail_array) && $thumbnail_array !='' )
			{	
				$image_name =$id."_thumb.".$thumbnail_array['type'];
				$thumbnail_image_file = $institute_id."/".$id."/".$image_name;	
			//	echo "<br>".$thumbnail_image_file."<br>";
				$params = array();
				$sqltext="UPDATE asset SET ";
				$sqltext .="thumbnail =?";
				array_push($params,sql_escape($thumbnail_image_file));
				$sqltext .=" WHERE id=?";
				array_push($params,sql_escape($id));
				db_change_query($conn,$sqltext,$params);
				//	echo "<br>".$_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id<br>";
				if(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id"))
				{
					mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id", 0777); 
					mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$id", 0777); 
				}
				elseif(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$id"))
				{
					mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$id", 0777); 
				}
				//$image_name =$id."_thumb".$thumbnail_array['type'];
				
				$savefile = fopen($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$thumbnail_image_file", 'w');
				fwrite($savefile, $thumbnail_array['image']);
				fclose($savefile);
				//echo $site_http."images/".$thumbnail_image_file;
				//$content=	file_get_contents($site_http."images/".$thumbnail_image_file);
	//echo '<img src="data:image/jpg;base64,' .$content. '" />';
			}
	
			//insert presenter
			//if($first_name !='' && $last_name !='')
			//{
			if(isset($presenters_array))
			{
					
				for($i=0;$i<count($presenters_array); $i++)
				{
					 $familyName= '';
					$givenName= '';
					$middleName= '';
					$suffix= ''; 
					$altName= ''; 
					$title= ''; 
					$department= ''; 
					$company= ''; 	
					foreach($presenters_array[$i] as $key=>$value)
					{
						 $$key = trim($value);
					}				
					
					$sqltext="INSERT INTO presenter(asset_id, first_name, last_name, middle_name, alt_name, suffix, title, department, organization) values( ?, ?, ?, ?, ? ,?,?,?,?)";
					$params = array();
					array_push($params,sql_escape($id));
					array_push($params,sql_escape($givenName));
					array_push($params,sql_escape($familyName));
					array_push($params,sql_escape($middleName));
					array_push($params,sql_escape($altName));
					array_push($params,sql_escape($suffix));
					array_push($params,sql_escape($title));// job title
					array_push($params,sql_escape($department));
					array_push($params,sql_escape($company));
					db_change_query($conn,$sqltext,$params);
				}
						
			}
				//insert keywords
				
			if(isset($keyword_array) &&  $keyword_array!='')
			{
				for($k_num=0; $k_num<count($keyword_array); $k_num++)
				{
					$sqltext="INSERT INTO keyword(asset_id, keyword) values( ?, ?)";
					$params = array();
					array_push($params,sql_escape($id));
					array_push($params,sql_escape($keyword_array[$k_num]));
					db_change_query($conn,$sqltext,$params);
				}
			}
				//insert timecode
			if(isset($timecode_array))
			{
				
				for($i=0;$i<count($timecode_array); $i++)
				{
					$timecode= ''; 
					$timecode_type= ''; 
					$data= ''; 
					foreach($timecode_array[$i] as $key=>$value)
					{
						 $$key = trim($value);
					}	
					$sqltext="INSERT INTO timecode(asset_id, timecode, timecode_type, data) values( ?, ?,?,?)";
					$params = array();
					array_push($params,sql_escape($id));
					array_push($params,sql_escape($timecode));
					array_push($params,sql_escape($timecode_type));
					array_push($params,sql_escape($data));
					db_change_query($conn,$sqltext,$params);
				}
			}
					//insert msc_number
			if(isset($msc_array) &&  $msc_array!='')
			{
				for($m_num=0; $m_num<count($msc_array); $m_num++)
				{
					$sqltext="INSERT INTO msc_number(asset_id, msc) values( ?, ?)";
					$params = array();
					array_push($params,sql_escape($id));
					array_push($params,sql_escape($msc_array[$m_num]));
					db_change_query($conn,$sqltext,$params);
				}
			}
			//add to api log
			$sqltext="INSERT INTO api_logs(query,added_date,user_id, institute_id,asset_id) values( ?, ?, ?,?,?)";
			$params = array();
			array_push($params,'Insert');
			array_push($params,date("Y-m-d H:i:s"));
			array_push($params,sql_escape($user_id));
			array_push($params,sql_escape($institute_id));
			array_push($params,sql_escape($id));
			db_change_query($conn,$sqltext,$params);
			
			unset($result_array);
			$result_array['assetID']=$id;		
			$result_array['assetURL']=$site_http."metadata/v1/asset/".$id;		
			$result_array['assetSHA1']=$asset_sha1;	
		//print_r($result_array);
			header('HTTP/1.1 201 Created. Asset was successfully inserted to the catalog.');
		//	echo json_encode($result_array);
			$result=json_encode($result_array);
			if(isset($_REQUEST['callback']))
			{  
				echo $_REQUEST['callback']. '(' . $result . ');';
				return;
			}
			echo $result;
			//echo "HTTP/1.1 201 Created <br />";
			//echo "Date: ".gmdate('D, j F Y g:i:s')." GMT<br />";
			//echo "Content-Type: application/json<br />";
			//echo "Location: ".$site_http."metadata/v1/asset/$id<br />";
		/*	echo "{ <br />\"assetID\": $id, <br />
							\"assetURL\": ".$site_http."metadata/v1/asset/$id <br />
							\"assetSHA1\": \"".$asset_sha1."\"<br />
							}";
			*/
		}
		else
		{
			//$error_message= "{\"error\": \"This asset already exists in our system!\"}";
			header('HTTP/1.1 400 Bad Request');
			echo  "{\"error\": \"This asset already exists in our system!\"}";
			exit;					
		}
	}	
	else
	{
		header('HTTP/1.1 400 Bad Request ');
		echo $error_message;
	}
}
?>
